package com.sbpm.crmbpm.client.panels.views;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sbpm.crmbpm.client.application.dict.Dictionaries;
import com.sbpm.crmbpm.client.forms.controls.CompanyComboBox;
import com.sbpm.crmbpm.client.forms.controls.SegmentComboBox;
import com.sbpm.crmbpm.client.forms.controls.SelectableListBox;
import com.sbpm.crmbpm.client.grid.AddressGrid;
import com.sbpm.crmbpm.client.handlers.LoadCompanyCallbackInMainView;
import com.sbpm.crmbpm.client.panels.*;
import com.sbpm.crmbpm.client.resources.css.CommonStylesCss;
import com.sbpm.crmbpm.client.services.CompanyManagement;
import com.sbpm.crmbpm.client.services.CompanyManagementAsync;
import com.sbpm.crmbpm.client.util.SimpleAsyncCallback;
import com.sbpm.crmbpm.shared.data.client.Address;
import com.sbpm.crmbpm.shared.data.client.Company;
import com.sbpm.crmbpm.shared.data.client.CompanyType;
import com.sbpm.crmbpm.shared.data.client.Segment;
import com.sencha.gxt.core.client.dom.ScrollSupport;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.box.MessageBox;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.*;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.*;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.info.DefaultInfoConfig;
import com.sencha.gxt.widget.core.client.info.Info;
import com.sencha.gxt.widget.core.client.info.InfoConfig;

public class MainView extends Viewport
{
    public static final int LABEL_WIDTH = 170;

    private final CommonStylesCss commonStylesCss = GWT.create( CommonStylesCss.class );

    private static final CompanyManagementAsync companyManagement = GWT.create( CompanyManagement.class );


    private BorderLayoutContainer mainViewContainer;

    private CompanyComboBox searchField;

    private Long companyId;
    private TextField companyName;
    private TextField legalName;
    private SegmentComboBox segment;
    private TextField inn;
    private TextField ogrn;
    private TextField kpp;

    private AddressGrid addressGrid;


    private HorizontalLayoutContainer searchLayout;

    public MainView()
    {
        int sideWidth = ( int )( Window.getClientWidth() / 4 );

        final BorderLayoutContainer mainViewContainer = new BorderLayoutContainer();
        add( mainViewContainer, new MarginData( 10 ) );
        mainViewContainer.setBorders(true);
        mainViewContainer.setResize( true );


        ContentPanel west = new ContentPanel();
        ContentPanel center = new ContentPanel();
        center.setHeadingText( "Клиент" );

        center.add( createCenterLayout() );

        ContentPanel east = new ContentPanel();

        BorderLayoutContainer.BorderLayoutData westData = new BorderLayoutContainer.BorderLayoutData( sideWidth );
        westData.setCollapsible(true);
        westData.setMargins(new Margins(0, 8, 0, 5));

        MarginData centerData = new MarginData();

        BorderLayoutContainer.BorderLayoutData eastData = new BorderLayoutContainer.BorderLayoutData( sideWidth );
        eastData.setMargins(new Margins(0, 5, 0, 8));
        eastData.setCollapsible(true);

        mainViewContainer.setWestWidget(west, westData);
        mainViewContainer.setCenterWidget( center, centerData );
        mainViewContainer.setEastWidget(east, eastData);


    }

    private Container createCenterLayout()
    {
        final FlowLayoutContainer container = new FlowLayoutContainer();
        container.setScrollMode( ScrollSupport.ScrollMode.ALWAYS );

//        container.setVBoxLayoutAlign( VBoxLayoutContainer.VBoxLayoutAlign.STRETCH );

        HBoxLayoutContainer topDataContainer = createDataWidgets();
        container.add( topDataContainer );

        Container searchLayout = createSearchWidgets();
        container.add( searchLayout );

        container.add( createClientForm(), new BoxLayoutContainer.BoxLayoutData( new Margins( 10, 10, 10, 10 ) ) );

        return container;
    }


    private Container createClientForm()
    {
        VerticalLayoutContainer formContainer = new VerticalLayoutContainer();
//        formContainer.setVBoxLayoutAlign( VBoxLayoutContainer.VBoxLayoutAlign.STRETCH );

        CollapsibleFormFieldSet mainDataForm = createMainDataForm();
        TextButton saveButton = new TextButton( "Сохранить" );
        mainDataForm.addButton( saveButton );

        saveButton.addSelectHandler( new SelectEvent.SelectHandler()
        {
            @Override
            public void onSelect( SelectEvent event )
            {
                saveCompany();
            }
        } );

        formContainer.add( mainDataForm, new VerticalLayoutContainer.VerticalLayoutData( -1, -1, new Margins( 5, 0, 0, 0 ) ) );

        CollapsibleFormFieldSet additionalDataForm = createAdditionalDataForm();
        formContainer.add( additionalDataForm, new VerticalLayoutContainer.VerticalLayoutData( -1, -1, new Margins( 5, 0, 0, 0 ) ) );
//        additionalDataForm.collapse();

        formContainer.add( createAddressDataForm(), new VerticalLayoutContainer.VerticalLayoutData( -1, -1, new Margins( 5, 0, 0, 0 ) ) );



        return formContainer;
    }



    private CollapsibleFormFieldSet createMainDataForm()
    {
        CollapsibleFormFieldSet fieldSet = new CollapsibleVBoxFormFieldSet( "Клиент" );
//        fieldSet.expand();
        fieldSet.setCollapsible( false );

        companyName = new TextField();
        fieldSet.getContainer().add( createLabel( companyName, "Наименование" ) );

        legalName = new TextField();
        fieldSet.getContainer().add( createLabel( legalName, "Юридическое название" ) );

        inn = new TextField();
        kpp = new TextField();
//        fieldSet.getContainer().add( createFieldLine( new FieldLabel( inn, "ИНН" ), new FieldLabel( kpp, "КПП" ) ) );
        fieldSet.getContainer().add( createLabel( inn, "ИНН" ) );
        fieldSet.getContainer().add( createLabel( kpp, "КПП" ) );
        ogrn = new TextField();

        segment = new SegmentComboBox();

//        fieldSet.getContainer().add( createFieldLine( new FieldLabel( ogrn, "ОГРН" ), new FieldLabel( segment, "Сегмент" ) ) );
        fieldSet.getContainer().add(createLabel( ogrn, "ОГРН" ));
        fieldSet.getContainer().add(createLabel( segment, "Сегмент" ));
        return fieldSet;
    }

    private Widget createAddressDataForm()
    {
        CollapsibleFormFieldSet fieldSet = new CollapsibleVerticalFormFieldSet( "Адрес" );

        addressGrid = new AddressGrid();

        fieldSet.getContainer().add( addressGrid );

        TextButton addAddress = new TextButton( "Добавить" );
        fieldSet.getContainer().add( addAddress );
        addAddress.addSelectHandler( new SelectEvent.SelectHandler()
        {
            @Override
            public void onSelect( SelectEvent event )
            {

                Address address = new Address();

                address.setCity( Dictionaries.CITIES.values().iterator().next().values().iterator().next() );

                addressGrid.getGridEditing().cancelEditing();
                addressGrid.getStore().add( address );

                addressGrid.getGridEditing().startEditing( new Grid.GridCell( addressGrid.getStore().getAll().size() - 1, 0 ) );
            }
        } );


//return addressGrid;
        return fieldSet;
//        formContainer.add( fieldSet, new BoxLayoutContainer.BoxLayoutData( new Margins( 2, 0, 0, 0 ) ) );
    }

    private CollapsibleFormFieldSet createAdditionalDataForm()
    {

        CollapsibleFormFieldSet fieldSet = new CollapsibleVBoxFormFieldSet( "Характеристика" );

        fieldSet.getContainer().add( createLabel( new TextField(), "Альтернативное название" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "ОПФ" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "Количество персонала" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "ФОТ" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "Дата открытия" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "Сайт" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "Годовой оборот" ) );

        fieldSet.getContainer().add( createLabel( new TextField(), "Отрасль" ) );

/*
        fieldSet.getContainer().add( createFieldLine( new FieldLabel( new TextField(), "Альтернативное название" ), new FieldLabel( new TextField(), "ОПФ" ) ) );
        fieldSet.getContainer().add( createFieldLine( new FieldLabel( new TextField(), "Количество персонала" ), new FieldLabel( new TextField(), "ФОТ" ) ) );
        fieldSet.getContainer().add( createFieldLine( new FieldLabel( new TextField(), "Дата открытия" ), new FieldLabel( new TextField(), "Сайт" ) ) );
        fieldSet.getContainer().add( createFieldLine( new FieldLabel( new TextField(), "Отрасль" ), new FieldLabel( new TextField(), "Годовой оборот" ) ) );

*/
        return fieldSet;

//        formContainer.add( fieldSet, new BoxLayoutContainer.BoxLayoutData( new Margins( 2, 0, 0, 0 ) ) );
    }

    private FieldLabel createLabel( IsWidget widget, String label )
    {
        FieldLabel fieldLabel = new FieldLabel( widget, label );
        fieldLabel.setLabelWordWrap( false );
        fieldLabel.setLabelWidth( LABEL_WIDTH );
        return fieldLabel;
    }

    private Container createFieldLine( Widget field1, Widget field2 )
    {
        return new FormLine( field1, field2 );
    }

    private Container createSearchWidgets()
    {
        VBoxLayoutContainer stretch = new VBoxLayoutContainer();
        stretch.setVBoxLayoutAlign( VBoxLayoutContainer.VBoxLayoutAlign.STRETCH );

        final HBoxLayoutContainer searchLayout = new HBoxLayoutContainer();
        searchLayout.setBorders( true );

        HBoxLayoutContainer.BoxLayoutData searchFieldData = new BoxLayoutContainer.BoxLayoutData();
        searchFieldData.setFlex( 1 );
        searchFieldData.setMinSize( 400 );
        searchFieldData.setMargins( new Margins( 10, 10, 10, 10 ) );

        searchField = new CompanyComboBox( new LoadCompanyCallbackInMainView( this ) );
        searchField.setEmptyText( "Введите название клиента, ИНН, ОГРН, паспортные данные..." );

        searchLayout.add( searchField, searchFieldData );

        TextButton searchButton = new TextButton( "Поиск" );
        HBoxLayoutContainer.BoxLayoutData searchButtonData = new BoxLayoutContainer.BoxLayoutData();
        searchButtonData.setMargins( new Margins( 10, 10, 10, 0 ) );

        searchLayout.add( searchButton, searchButtonData );
        stretch.add( searchLayout );

        return stretch;
    }

    private HBoxLayoutContainer createDataWidgets()
    {
        HBoxLayoutContainer topDataContainer = new HBoxLayoutContainer();
        topDataContainer.setBorders( true );

        FlexTable notificationDataBox = createDataBox( 1, 2, 3, 4);
        topDataContainer.add( notificationDataBox );

        FlexTable clientDataBox = createDataBox( 5, 676, 434, 4);
        topDataContainer.add( clientDataBox );
        return topDataContainer;
    }

    private FlexTable createDataBox( int param1, int param2, int param3, int param4)
    {
        return new DataBox( param1, param2, param3, param4 );
    }


    public void loadCompany( Company company )
    {
        clearData();
        companyId = company.getId();
        companyName.setValue( company.getName() );
        legalName.setValue( company.getLegalName() );
        if( company.getSegment() != null )
        {
            segment.setValue( company.getSegment() );
        }
        inn.setValue( company.getInn() );
        ogrn.setValue( company.getOgrn() );
        kpp.setValue( company.getKpp() );
        if( company.getAddresses() != null )
        {
            addressGrid.getStore().addAll( company.getAddresses() );
        }
    }

    public void clearData()
    {
        companyId = null;
        companyName.setValue( "" );
        legalName.setValue( "" );
        segment.setValue( null );
        inn.setValue( "" );
        ogrn.setValue( "" );
        kpp.setValue( "" );
        addressGrid.getStore().clear();
    }

    public void saveCompany()
    {
        Company company = new Company();
        company.setId( companyId );
        company.setInn( inn.getCurrentValue() );
        company.setKpp( kpp.getCurrentValue() );
        company.setLegalName( legalName.getCurrentValue() );
        company.setName( companyName.getCurrentValue() );
        company.setOgrn( ogrn.getCurrentValue() );
        if( segment.getCurrentValue() != null )
        {
            company.setSegment( segment.getCurrentValue() );
        }
        company.setType( CompanyType.CLIENT );
        companyManagement.saveCompany( company, new SimpleAsyncCallback()
        {
            @Override
            public void onSuccess( Object result )
            {
                DefaultInfoConfig config = new DefaultInfoConfig( "", "Данные сохранены" );
                config.setPosition( InfoConfig.InfoPosition.TOP_RIGHT );
                config.setDisplay( 3000 );
                Info.display( config );
            }
        }  );
    }
}
